package com.wmsafe.order.excelService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wmsafe.order.utils.ExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Service
public class ExportService {

    public <T> void exportData(String fileName, BaseMapper<T> mapper, QueryWrapper<T> queryWrapper, int batchSize) {
        // 查询总记录数
        Long totalCount = mapper.selectCount(queryWrapper);

        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<CompletableFuture<Object>> futures = new ArrayList<>();

        // 分批次导出数据
        for (int i = 0; i < totalCount; i += batchSize) {
            int startRow = i + 1;

            // 提交任务到线程池
            CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> {
                        try {
                            // 自定义 QueryWrapper 查询指定范围的数据
                            Page<T> page = new Page<>(startRow, batchSize);
                            List<T> dataList = mapper.selectPage(page, queryWrapper).getRecords();

                            // 导出数据为 Excel 文件
                            ExcelWriter excelWriter = EasyExcel.write(fileName, dataList.get(0).getClass())
                                    .registerWriteHandler(ExportUtil.getHorizontalCellStyleStrategy())
                                    .registerWriteHandler(new CustomizeHeaderStyleHandler())
                                    .build();


                            WriteSheet writeSheet = EasyExcel.writerSheet().build();

                            excelWriter.write(dataList, writeSheet);
                            excelWriter.finish();
                            return null;
                        } catch (Exception e) {
                            // 异常处理
                            throw new CompletionException(e);
                        }
                    }, executorService)
                    .exceptionally(ex -> {
                        // 异常处理
                        handleExportError(ex);
                        return null;
                    });

            futures.add(future);
        }

        // 等待所有任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .whenComplete((result, ex) -> {
                    // 关闭线程池
                    executorService.shutdown();
                })
                .join();
    }

    private void handleExportError(Throwable ex) {
        // 错误处理逻辑，可以根据需要自定义
        System.out.println("导出失败，请重新导出。错误信息：" + ex.getMessage());
        throw new CompletionException(ex);
    }


}

